from DBUtility import DBManage
from Verification import Verification


class Manage:
    def __init__(self):
        self.employee = EmployeeManage()  # 实例化员工管理类
        self.recruit = RecruitManage()  # 实例化招聘管理类
        self.user = UserManage()  # 实例化用户管理类
        self.verify = Verification()  # 实例化校验类
        self.db = DBManage()

    def main_view(self):
        """管理端主界面"""
        while True:
            choice = input("""\033[36m 
            欢迎进入管理系统
              1.员工管理
              2.招聘管理
              3.用户信息
              0.退出
            请选择操作:\033[0m""")
            try:
                if choice == '1':
                    self.employee_view()
                elif choice == '2':
                    self.recruit_view()
                elif choice == '3':
                    self.user_view()
                elif choice == '0':
                    break
                else:
                    print('\033[31m选择有误！请重新选择！\033[0m')
            except Exception as e:
                print(f'\033[31m{e}\033[0m')

    def employee_view(self):
        """员工管理界面"""
        while True:
            try:
                choice = input("""\033[36m
                欢迎进入员工管理系统
                  1.查看员工
                  2.查询员工
                  3.修改员工信息
                  4.删除员工信息
                  5.处理请假信息
                  0.返回
                请选择操作:\033[0m""")
                if choice == '1':
                    self.employee.show_data()
                elif choice == '2':
                    self.employee.select_data()
                elif choice == '3':
                    self.employee.update_data()
                elif choice == '4':
                    self.employee.delete_data()
                elif choice == '5':
                    self.employee.leave_data()
                elif choice == '0':
                    self.db.refresh_connection()  # 刷新连接
                    break
                else:
                    print('\033[31m选择有误！请重新选择！\033[0m')
            except Exception as e:
                print(f'\033[31m{e}\033[0m')

    def recruit_view(self):
        """招聘管理界面"""
        while True:
            choice = input("""\033[36m 
            欢迎进入招聘管理系统
              1.查看招聘信息
              2.查看应聘人
              3.添加招聘信息
              4.处理应聘信息
              5.删除未应聘信息
              0.返回
            请选择操作:\033[0m""")
            try:
                if choice == '1':
                    self.recruit.show_data("1")
                elif choice == '2':
                    self.recruit.show_data("2")
                elif choice == '3':
                    self.recruit.add_job()
                elif choice == '4':
                    self.recruit.update_data()
                elif choice == '5':
                    self.recruit.delete_resume()
                elif choice == '0':
                    break
                else:
                    print('\033[31m选择有误！请重新选择！\033[0m')
            except Exception as e:
                raise Exception(f'\033[31m{e}\033[0m')

    def user_view(self):
        while True:
            choice = input("""\033[36m
            欢迎进入用户管理系统
              1.查看用户
              2.删除用户
              0.返回
            请选择操作:\033[0m""")
            try:
                if choice == '1':
                    self.user.show_data()
                elif choice == '2':
                    self.user.delete_data()
                elif choice == '0':
                    break
                else:
                    print('\033[31m选择有误！请重新选择！\033[0m')
            except Exception as e:
                raise Exception(f'\033[31m{e}\033[0m')


# 员工管理工具类
class EmployeeManage:
    def __init__(self):
        self.db = DBManage()
        self.verify = Verification()

    def show_data(self):
        """展示所有员工信息"""
        try:
            print(self.db.show_data('tb_employee'))
        except Exception as e:
            raise Exception(f'\033[31m{e}\033[')

    def add_data(self, datas: dict):
        """添加用户信息"""
        try:
            self.db.add_data('tb_employee', datas)
            print("添加成功！")
        except Exception as e:
            raise Exception(f'\033[31m{e}\033[0m')

    def select_data(self):
        """关键字查询"""
        key = input("请输入查询关键字（姓名/电话/职位）:")
        if key:
            try:
                condition = f"name='{key}' or phone='{key}' or job='{key}'"
                result = self.db.select_data('tb_employee', condition)
                if result:
                    print(result)
                else:
                    print("没有查询到信息！")
            except Exception as e:
                raise Exception(f'\033[31m{e}\033[0m')
        else:
            print("关键字不能为空")

    def update_data(self):
        """更改员工信息"""
        try:
            employID = int(input("请输入要更改员工的ID: "))
            if self.verify.enter_validation(employID):  # 输入验证
                condition = f"employID={employID}"
                result = self.db.select_data('tb_employee', condition)
                if result:
                    job = input("请输入新职位: ")
                    performance = int(input("请输入绩效: "))
                    salary = int(input("请输入底薪: "))
                    args = [job, performance, salary]
                    if self.verify.enter_validation(*args):  # 输入验证
                        updates = {'job': job, 'performance': performance, 'salary': salary}  # 要更改值的字典
                        condition = f'employID={employID}'
                        self.db.update_data('tb_employee', updates, condition)
                        self.db.update_data('tb_user', {'job': job}, condition)
                        print("更改成功！")
                else:
                    print("未找到该员工！")
        except Exception as e:
            raise Exception(f'\033[31m{e}\033[0m')

    def delete_data(self):
        """删除员工数据"""
        try:
            employID = int(input('请输入员工ID:'))
            if self.verify.enter_validation((employID,)):  # 输入校验
                condition = f"employID={employID}"
                # 查询对应的信息
                result = self.db.select_data('tb_employee', condition)
                if result:
                    phone = result[0][2]  # 获取手机号！
                    print(result)
                    choice = input("是否删除该员工？(Y/y) or (N/n):").lower()
                    if choice == "y":
                        # 删除对应的员工信息
                        self.db.delete_data('tb_employee', condition)
                        # 更新用户信息
                        datas = {'employID': 'NULL', 'job': '无业游民'}  # 要更新用户的信息
                        self.db.update_data('tb_user', datas, condition)
                        # 删除相关请假信息
                        self.db.delete_data('tb_leave', condition)
                        # 删除相关简历信息
                        condition = f"phone='{phone}'"
                        self.db.delete_data('tb_resume', condition)
                        print("删除成功！")
                    else:
                        print("已取消！")
                else:
                    print("员工不存在！")
        except Exception as e:
            raise Exception(f'\033[31m{e}\033[0m')

    def leave_data(self):
        """员工请假信息处理"""
        leave_db = DBManage()  # 实例化请假数据类
        try:
            result = leave_db.show_data('tb_leave')
            if result:
                print(result)  # 打印请假条数据
                Id = int(input("请输入请假单号:"))
                employID = int(input("请输入员工ID:"))
                args = [Id, employID]
                if self.verify.enter_validation(*args):  # 输入校验
                    condition_l = f"id = {Id} and employID = {employID} and pass is NULL"
                    condition = f"employID = {employID}"
                    #  查询对应的结果！
                    result = leave_db.select_data('tb_leave', condition_l)
                    if result:
                        print(result)
                        choice = input("是否同意？（Y/y) or (N/n): ").lower()
                        if choice == "y":
                            datas = {'pass': 'Y'}
                            # 更改请假信息
                            leave_db.update_data('tb_leave', datas, condition_l)
                            # 获取相应员工表的数据
                            result = self.db.select_data('tb_employee', condition)
                            # 获取请假次数数据
                            datas_e = {'leaveD': f'{result[0][-3] + 1}'}
                            # 更改员工表的数据
                            self.db.update_data('tb_employee', datas_e, condition)
                            print("审核通过！")
                        elif choice == "n":
                            # 不予通过！修改请假条回执
                            datas = {'pass': 'N'}
                            leave_db.update_data('tb_leave', datas, condition_l)
                            print("审核不通过")
                        else:
                            print("输入有误！")
                    else:
                        print("员工不存在或信息已经处理！")
        except Exception as e:
            raise Exception(f'\033[31m{e}\033[0m')


# 招聘管理类
class RecruitManage:
    def __init__(self):
        self.db = DBManage()  # 实例化工具类！
        self.verify = Verification()  # 实例化校验类

    def show_data(self, choice):
        """显示所有招聘信息"""
        if choice == "1":
            try:
                result = self.db.show_data('tb_recruit')
                if result:
                    print(result)
                else:
                    print("没有招聘信息！请发布！")
            except Exception as e:
                raise Exception(f"\033[31m{e}\033[0m")
        elif choice == "2":
            try:
                result = self.db.show_data('tb_resume')
                if result:
                    print(result)
                else:
                    print("没有人应聘！")
            except Exception as e:
                raise Exception(f"\033[31m{e}\033[0m")

    def add_job(self):
        """添加招聘信息"""
        try:
            job = input("请输入职位: ")
            salary = int(input("请输入薪水: "))
            description = input("请输入职位描述: ")
            args = [job, salary, description]
            if self.verify.enter_validation(*args):
                datas = {'job': job, 'salary': salary, 'info': description}
                self.db.add_data('tb_recruit', datas)
                print("招聘信息添加成功！")
        except Exception as e:
            raise Exception(f"\033[31m{e}\033[0m")

    def update_data(self):
        """处理应聘信息"""
        phone = input("请输入应聘者电话: ")
        try:
            if self.verify.enter_validation((phone,)):
                # 处理未处理的请假信息！
                condition = f"phone = '{phone}' and pass is NULL"
                result = self.db.select_data('tb_resume', condition)
                if result:
                    print(result)
                    choice = input("确定录用吗？'（Y/y）' 或 '(N/n)': ").lower()
                    if choice == 'y':
                        datas = {'pass': 'Y'}
                        # 更改简历信息
                        self.db.update_data('tb_resume', datas, condition)
                        resume_class = EmployeeManage()  # 实例化员工管理类
                        # 添加员工信息
                        datas_r = {'name': result[0][1], 'phone': result[0][2], 'job': result[0][3],
                                   'salary': result[0][4]}  # 要添加的信息
                        resume_class.add_data(datas_r)
                    elif choice == 'n':
                        datas = {'pass': 'N'}
                        self.db.update_data('tb_resume', datas, condition)
                    else:
                        print("\033[31m无效选择，请重新输入！\033[0m")
                else:
                    print("未找到该应聘者！")
        except Exception as e:
            raise Exception(f"\033[31m{e}\033[0m")

    def delete_resume(self):
        """删除应聘信息"""
        try:
            Id = int(input("请输入简历编号:"))
            phone = input("请输入手机号:")
            args = [Id, phone]
            condition = f"id = {Id} and phone = '{phone}' and pass='N'"
            if self.verify.enter_validation(*args):
                # 查询对应的结果
                result = self.db.select_data('tb_resume', condition)
                if result:
                    choice = input("确定删除吗？(Y/y),任意键取消...:").lower()
                    if choice == 'y':
                        # 删除当前数据
                        self.db.delete_data('tb_resume', condition)
                        print("简历删除成功！")
                    else:
                        print("取消删除简历！")
                else:
                    print("未找到该简历")
        except Exception as e:
            raise Exception(f"\033[31m{e}\033[0m")


# 用户管理类
class UserManage:
    def __init__(self):
        self.db = DBManage()
        self.verify = Verification()

    def show_data(self):
        """显示所有用户数据"""
        try:
            result = self.db.show_data('tb_user')
            if result:
                print(result)
            else:
                print("没有用户数据！")
        except Exception as e:
            raise Exception(f"\033[31m{e}\033[0m")

    def delete_data(self):
        """删除用户数据"""
        phone = input("请输入要删除的用户电话: ")
        try:
            if self.verify.enter_validation(phone):  # 输入校验
                condition = f"phone = '{phone}'"
                # 查询对应的数据
                result = self.db.select_data('tb_user', condition)
                if result:
                    print(result)
                    choice = input("确定删除吗？(Y/y) or （N/n):").lower()
                    if choice == 'y':
                        # 删除用数据
                        self.db.delete_data('tb_user', condition)
                        print("用户删除成功！")
                    elif choice == 'n':
                        print("已取消！")
                    else:
                        print("\033[31m无效选择，请重新输入！\033[0m")
                else:
                    print("未找到该用户！")
        except Exception as e:
            raise Exception(f"\033[31m{e}\033[0m")
